package com.neo.rabbit.hello;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class HelloSender implements RabbitTemplate.ReturnCallback{

	private final RabbitTemplate rabbitTemplate;

	public HelloSender(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
		this.rabbitTemplate.setReturnCallback(this);
		this.rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause) -> {
			if (!ack) {
				System.out.println("消息发送失败"+cause);
			}
            else {
				System.out.println("消息发送成功 ");
            }
		});
	}

	/***
	 * @description  普通消息队列
	 * @author 车欢 (chehuan@bosssoft.com.cn) <br>
	 * @date 2021/10/26 11:34
	 * @param msg
	 * @param exchange
	 * @param queueRoutingKey
	 * @return void
	 */
	public void sendOrdinaryMessage(String msg, String exchange, String queueRoutingKey) {
		// 设置发送时间，开始发送
		try {
			this.rabbitTemplate.convertAndSend(exchange, queueRoutingKey, msg);
		} catch (AmqpException e) {
//            log.error("消息发送失败，请检查消息中间件是否正常", e);
//            log.error("消息发送失败，请检查消息中间件是否正常 {}", JSONObject.toJSONString(msg));
			throw new RuntimeException("消息队列,发送失败");
		}
	}

	@Override
	public void returnedMessage(Message message, int i, String s, String s1, String s2) {
//		System.out.println(String.join("sender return success {} {} {} {}", message.toString(), i, s1, s2));
		System.out.println("sender return success");
	}
}